import 'dart:async';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class VideoPlayerScreen extends StatefulWidget {
  VideoPlayerScreen({
    super.key,
    required this.url,
    this.onState,
  });
  final String url;

  Function(VideoPlayerController)? onState;
  @override
  State<VideoPlayerScreen> createState() => _VideoPlayerScreenState();
}

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  late final VideoPlayerController _controller = VideoPlayerController.networkUrl(
    Uri.parse(widget.url),
  );
  late Future<void> future;
  @override
  void initState() {
    super.initState();
    _controller.setLooping(true);
    future = _controller.initialize();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {

    return FutureBuilder(
      future: future,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return AspectRatio(
            aspectRatio: _controller.value.aspectRatio,
            child: Stack(
              alignment: Alignment.center,
              children: [
                VideoPlayer(_controller),
                IconButton(
                  onPressed: () async {
                    if (_controller.value.isPlaying) {
                      await _controller.pause();
                    } else {
                      await _controller.play();
                    }
                    if (widget.onState != null) {
                      widget.onState!(_controller);
                    }
                    setState(() {

                    });
                  },
                  icon: _controller.value.isPlaying
                      ? Icon(Icons.pause, color: Colors.white.withAlpha(900))
                      : const Icon(Icons.play_arrow, color: Colors.white),
                  iconSize: 64,
                ),
              ],
            ),
          );
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }
}
